package com.lht.cozyCloud.gateway.service.impl;

import com.google.code.kaptcha.Producer;
import com.lht.cozyCloud.common.core.constant.CacheConstants;
import com.lht.cozyCloud.common.core.constant.Constants;
import com.lht.cozyCloud.common.core.exception.CaptchaException;
import com.lht.cozyCloud.common.core.text.Convert;
import com.lht.cozyCloud.common.core.utils.StringUtils;
import com.lht.cozyCloud.common.core.utils.sign.Base64;
import com.lht.cozyCloud.common.core.utils.uuid.IdUtils;
import com.lht.cozyCloud.common.core.utils.uuid.UUID;
import com.lht.cozyCloud.common.core.web.domain.AjaxResult;
import com.lht.cozyCloud.common.redis.service.RedisService;
import com.lht.cozyCloud.gateway.config.properties.CaptchaProperties;
import com.lht.cozyCloud.gateway.service.PhoneValidateCodeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.FastByteArrayOutputStream;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;
import java.util.concurrent.TimeUnit;

/**
 * 手机验证码实现处理
 *
 * @author ruoyi
 */
@Service
public class PhoneValidateCodeServiceImpl implements PhoneValidateCodeService
{
    @Autowired
    private RedisService redisService;

    /**
     * 生成验证码
     */
    @Override
    public AjaxResult createCaptcha() throws CaptchaException
    {
        AjaxResult ajax = AjaxResult.success();
        // 保存验证码信息
        String uuid = IdUtils.simpleUUID();
        String verifyKey = CacheConstants.PHONE_CODE_KEY + uuid;

        Random random = new Random();
        int min = 0; // 最小值（包含）
        int max = 9999; // 最大值（包含）
        int i = random.nextInt((max - min) + 1) + min;
        String code = String.format("%04d", i);

        // 有效期1分钟
        redisService.setCacheObject(verifyKey, code, 1L, TimeUnit.MINUTES);

        ajax.put("uuid", uuid);
        return ajax;
    }

    /**
     * 校验验证码
     */
    @Override
    public void checkCaptcha(String code, String uuid) throws CaptchaException
    {
        if (StringUtils.isEmpty(code))
        {
            throw new CaptchaException("验证码不能为空");
        }
        String verifyKey = CacheConstants.PHONE_CODE_KEY + StringUtils.nvl(uuid, "");
        String captcha = redisService.getCacheObject(verifyKey);
        if (captcha == null)
        {
            throw new CaptchaException("验证码已失效");
        }
        redisService.deleteObject(verifyKey);
        if (!code.equalsIgnoreCase(captcha))
        {
            throw new CaptchaException("验证码错误");
        }
    }
}
